package com.letoo.sso.core.service.impl;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.letoo.sso.common.utils.AssertUtil;
import com.letoo.sso.core.service.CounterService;
import com.letoo.sso.dataaccess.dao.cahce.CounterCacheDAO;
import com.letoo.sso.dataaccess.dao.db.CounterDBDAO;

/**
 * @author: dengjie
 */
@Service("counterService")
public class CounterServiceImpl implements CounterService {
    @Resource
    private CounterCacheDAO dao;
    @Resource
    private CounterDBDAO dbDao;

    @Override
    public Long nextCount(KeyType keyType) {
        return dao.nextCount(keyType.toString());
    }

    @Override
    public Long nextCountOfLength(KeyType keyType, int length) {
        return dao.nextCountOfLength(keyType.toString(), length);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Long nextCountByDb(KeyType keyType) {
        return nextCountOfLengthByDb(keyType, 1);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Long nextCountOfLengthByDb(KeyType keyType, int length) {
        return nextCountForResetTypeByDb(keyType, length);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public Long nextCountForResetTypeByDb(KeyType keyType, int length) {
        AssertUtil.notNull(keyType, "计数器类型不能为空");
        int updateCount = 0;
        updateCount = dbDao.updateNonResetCounter(keyType.toString(), length);
        AssertUtil.isTrue(updateCount > 0, String.format("类型：%s的计数器不存在", keyType.toString()));
        return dbDao.getCounter(keyType.toString());
    }
}
